package com.pmsystem.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.Driver;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Controller;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@ComponentScan(basePackages = "com.pmsystem", excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class))
public class RootConfig {
	@Bean
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		try {
			dataSource.setDriver(new Driver());
			dataSource.setUrl(
					"jdbc:mysql://localhost:3306/pmsystem?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=Hongkong");
			dataSource.setUsername("root");
			dataSource.setPassword("123456");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}
	

	@Bean(value = "sqlSessionFactoryBean")
	public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
		bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
		return bean;
	}

	@Bean
	public MapperScannerConfigurer mapperconfig() {
		MapperScannerConfigurer mp = new MapperScannerConfigurer();
		mp.setBasePackage("com.pmsystem.dao");
		mp.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
		return mp;
	}
}
